import axios from 'axios'
import config from '@/config/index'
import qs from 'qs'
import store from 'store'
import {
  Message
} from 'element-ui' // 按需引用element-ui组件

class API {
  constructor () {
    this.http = axios.create({
      timeout: 20000
    })
    // POST请求前将数据转化成FormData对象
    this.http.interceptors.request.use(config => {
      config.data = qs.stringify(config.data)

      // 判断是否存在token，如果存在的话，则每个http header都加上token
      if (store.get('token')) {
        config.headers['api-token'] = `${store.get('token')}`
      }
      return config
    })
  }
  get (url, data) {
    url = this.buildUrl(url)
    let params = {
      params: data
    }
    return this.http.get(url, params)
  }
  post (url, data) {
    url = this.buildUrl(url)
    return new Promise((resolve, reject) => {
      this.http.post(url, data).then(res => {
        var data = res.data
        if (data.code !== 200) {
          Message({
            message: data.msg,
            type: 'warning'
          })
          return
        }
        resolve(data)
      })
    })
  }
  buildUrl (url) {
    return config.path + url
  }
}

let api = new API()
export default api
